package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Creared with IntelliJ IDEA.
 * Description:这里处理博客详情页修改用户名的请求
 * User:yxd
 * Date:2022-06-05
 * Time:14:59
 */
@WebServlet("/authorInfo")
public class AuthorServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf8");
        //通过这里的请求来获取当前的文章,看其作者是谁,并返回回去
        String blogId = req.getParameter("blogId");
        if(blogId == null || "".equals(blogId)){
            //参数缺失,
            resp.getWriter().write("{\"ok\":false,\"reason\":\"参数缺失!\"}");
            return;
        }
        //然后再通过这个blogId来查询这篇文章
        BlogDao blogDao = new BlogDao();
        Blog blog = blogDao.select(Integer.parseInt(blogId));
        //看这篇文章是否存在
        if(blog == null){
            //当前文章不存在
            resp.getWriter().write("{\"ok\":false,\"reason\":\"要查询的文章不存在!\"}");
            return;
        }
        //然后通过这篇文章来查询当前的作者信息
        UserDao userDao = new UserDao();
        User user = userDao.selectById(blog.getUserId());
        if(user == null){
            //当前作者不存在
            resp.getWriter().write("{\"ok\":false,\"reason\":\"要查询的作者不存在!\"}");
            return;
        }

        //查到这里表示当前作者是存在的而且文章也是存在的,然后将这个作者信息写回
        //而这里不用把密码写回.因此就把密码设为空
        user.setPassword("");
        resp.getWriter().write(objectMapper.writeValueAsString(user));
    }
}
